package com.zjw.study.thread05_executor;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

import com.zjw.study.thread.ThreadUtils;

/**
 * 线程并发池
 * @author Administrator
 *
 */
public class ThreadPool {
	public static void main(String[] args) {
		ThreadPool pool = new ThreadPool();
//		pool.pool01();
//		pool.poolTimer();
		pool.poolTimer02();
	}
	
	/**
	 * 线程池 示例
	 */
	void pool01() {
		ExecutorService threadPool;
		//创建一个线程池，可同时执行3个线程
//		threadPool = Executors.newFixedThreadPool(3);
		//创建线程缓存池，个数随着线程的数量增加而增加，减少则释放
//		threadPool = Executors.newCachedThreadPool();
		//创建一个线程池，虽然只能运行一个线程，但优点是线程意外死掉后会自动重新启动一个新线程
		//注意：如果调shutDownNow()，线程将直接被杀死
		threadPool = Executors.newSingleThreadExecutor();
		
		//按照顺序每次同时执行3个线程
		for (int i = 1; i <= 10; i++) {
			final int task = i;
			threadPool.execute(new Runnable() {
				@Override
				public void run() {
					for (int j = 1; j <= 10; j++) {
						ThreadUtils.sleep(10);
						System.out.println(Thread.currentThread().getName() + " j=" + j + " task=" + task);
					}
				}
			});
		}
		if(!threadPool.isShutdown()) {
			threadPool.shutdown();//执行完关闭，一般使用此方法
//			System.out.println("停止的线程：" + threadPool.shutdownNow());//立即关闭，并返回未执行的线程
		}
	}
	
	/**
	 * 定时器的调用
	 */
	void poolTimer() {
		ScheduledExecutorService threadPool = Executors.newSingleThreadScheduledExecutor();
		threadPool.schedule(new Runnable() {
			
			@Override
			public void run() {
				System.out.println("timer execute...");
			}
		}, 2, TimeUnit.SECONDS);
		
		threadPool.shutdown();
//		threadPool.shutdownNow();//会直接停掉定时器
	}
	/**
	 * 定时器的调用（循环执行）
	 */
	void poolTimer02() {
		ScheduledExecutorService threadPool = Executors.newSingleThreadScheduledExecutor();
		threadPool.scheduleWithFixedDelay(new Runnable() {
			
			@Override
			public void run() {
				System.out.println("timer execute...");
			}
		}, 2, 4, TimeUnit.SECONDS);//2秒后启动，每4秒执行一次
		
//		threadPool.shutdown();//循环执行时，此方法也会导致线程立即停止
//		threadPool.shutdownNow();//会直接停掉定时器
	}

}
